package com.gitee.ly.ymorm.executor;

import com.gitee.ly.ymorm.YmOrmConfig;
import com.gitee.ly.ymorm.executor.handler.StatementHandler;
import com.gitee.ly.ymorm.log.YmOrmLog;
import com.gitee.ly.ymorm.mapping.ParamMap;
import com.gitee.ly.ymorm.mapping.YmOrmStatement;
import com.gitee.ly.ymorm.transaction.Transaction;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

/**
 * SimpleExecutor
 *
 * @author ly
 **/
public class SimpleExecutor extends BaseExecutor {
    public SimpleExecutor(YmOrmConfig configuration, Transaction transaction) {
        super(configuration, transaction);
    }

    @Override
    protected int doUpdate(YmOrmStatement ymOrmStatement, ParamMap paramMap) throws SQLException {
        Statement statement = null;
        try {
            YmOrmConfig configuration = ymOrmStatement.getConfiguration();
            StatementHandler statementHandler = configuration.newStatementHandler(this, ymOrmStatement, paramMap);
            statement = prepareStatement(statementHandler, ymOrmStatement.getLog());
            return statementHandler.update(statement);
        } finally {
            closeStatement(statement);
        }
    }

    private Statement prepareStatement(StatementHandler statementHandler, YmOrmLog log) throws SQLException {
        Statement stmt;
        Connection connection = getConnection(log);
        stmt = statementHandler.prepare(connection, transaction.getTimeout());
        statementHandler.parameterize(stmt);
        return stmt;
    }

    @Override
    protected <E> List<E> doQuery(YmOrmStatement ymOrmStatement, ParamMap paramMap, Class<? extends E> resultType) throws SQLException {
        Statement stmt = null;
        try {
            Connection connection = transaction.getConnection();
            Integer timeout = transaction.getTimeout();
            StatementHandler statementHandler = null;
            statementHandler.query(stmt, resultType);
        } finally {
            closeStatement(stmt);
        }
    }

}
